package com.itheima.demo08;

import java.util.Random;

public class RedPacketThead extends Thread {
    //抢红包线程

    //定义共享数据
    static double money = 100;//总金额

    static int count = 3;//红包数量

    final static double MIN = 0.01;//最小红包金额

    @Override
    public void run() {

        synchronized (RedPacketThead.class){ //代码块加同步锁
            //每个人只抢一次
            //1、先判断红包是否抢完
            if (count == 0) {
                System.out.println(getName() + "没有抢到红包");
            } else {
                double price = getPrice();
                System.out.println(getName() + "抢到了" + price + "元");

                money = money - price;//总金额 减去 已经随机到的金额 = 剩余红包的金额
                count--;//红包数-1
            }
        }

    }

    private static double getPrice() {//计算抢到的红包金额
        double price = 0;//抢到的红包金额
        if (count == 1) { //最后一个就等于剩余金额
            price = money;
        } else {
            //2.随机金额，并判断剩余金额
            Random random = new Random();
            double range = money - (count - 1) * MIN;// 100 - (count - 1) * MIN = 98.8 最终剩余的金额最大范围
            price = random.nextDouble() * range;
            if (price < MIN){//如果随机到的金额小于最小金额
                price = MIN;//就让红包金额等于最小金额
            }
        }
        return price;
    }
}
